local skynet = require "skynet"
local PlayerProto = require "modules.player.PlayerProto"
local PlayerService = require "modules.player.PlayerService"
local PlayerConst = require "modules.player.PlayerConst"
local Platform = require "global.Platform"
local Services = require "global.Services"
local Msger = require "core.Msger"
local BanService = require "modules.ban.BanService"
local Eventer = require "core.Eventer"
local PlayerEvent = require "modules.player.PlayerEvent"
---@type PlayerMgr
local PlayerMgr = Services.PLAYER_MGR

local handler = {}
function handler.CS_HEART_BEAT(player)
    return PlayerProto.HEART_BEAT
end

function handler.CS_LOGOUT(player)
    -- 记录日志等
    PlayerMgr:logout(player.id)
end

-- 登录是第一个请求，第一个参数是连接
function handler.CS_LOGIN(connection, data)
    local loginResultCode = PlayerConst.LOGIN_RESULT_CODE
    if PlayerService:onlineCount() >= PlayerConst.MAX_ONLINE_COUNT then
        return {
            code = loginResultCode.PLAYER_FULL,
            msg = "服务器人数已满"
        }
    end

    local ipBannedTime = BanService:ipBanned(connection.addr)
    if ipBannedTime then
        return {
            code = loginResultCode.IP_BANNED,
            msg = "ip被封禁"
        }
    end

    local code, authData = Platform.auth(data)
    if code ~= 1 then
        -- 授权失败
        GWARNF("auth failed, code: %s, msg: %s", code, authData)
        return {
            code = loginResultCode.AUTH_FAILED,
            msg = string.format("授权失败, 错误码: %s", code)
        }
    end

    local playerId = authData.id
    if BanService:playerBanned(playerId) then
        return {
            code = loginResultCode.PLAYER_BANNED,
            msg = "账号被封禁"
        }
    end

    -- 先踢掉原来的连接
    Msger.send(playerId, PlayerProto.KICK, {
        code = PlayerConst.KICK_REASON.LOGIN_OTHER_DEVICE
    })

    PlayerMgr:logout(playerId)
    if not PlayerMgr:login(playerId, connection.fd, connection.gate) then
        return {
            code = 3,
            msg = "玩家已经登录"
        }
    end

    local player = PlayerService:login(playerId)
    local RoomService = require "modules.room.RoomService"
    local roomId = RoomService:getPlayerRoom(playerId)
    
    -- 登录成功
    return {
        code = PlayerConst.LOGIN_RESULT_CODE.SUCCESS,
        player = player
    }
end

return handler
